<template>
  <div class="app-container datasview">
    <!-- 查询和其他操作 -->
    <div class="filter-container search">
      <el-input v-model="listQuery.title" clearable class="" style="width: 130px;" placeholder="请输入素材名称"/>
      <el-input v-model="listQuery.keywords" clearable class="" style="width: 130px;" placeholder="请输入关键字"/>
      <el-input v-model="listQuery.playId" clearable class="" style="width: 90px;" placeholder="录播ID"/>
      <div>
        <el-select v-model="listQuery.source" placeholder="请选择来源" style="width:130px;" clearable>
          <el-option
            v-for="item in sourceFormat"
            :key="item.value"
            :label="item.value"
            :value="item.key"/>
        </el-select>
      </div>
      <div>
        <el-cascader
          v-model="cateList"
          :options="cateOptions"
          :props="{
            expandTrigger: 'hover',
            value:'id',
            label:'name',
          }"
          clearable
          placeholder="请选择分类"
        />
      </div>
      <el-date-picker
        v-model="listQuery.beginTime"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetime"
        style="width:150px;"
        placeholder="选择开始日期"/>
      <el-date-picker
        v-model="listQuery.endTime"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetime"
        style="width:150px;"
        placeholder="选择结束日期"/>
      <div class="buttonGroup">
        <el-button class="filter_button" icon="el-icon-search" @click="handleFilter">查找</el-button>
        <el-button class="filter_button" @click="refresh">重置</el-button>

      </div>
    </div>
    <!-- 页面全局操作 -->
    <div class="buttons">
      <tagButton name="本页全部加水印" @click="addWatermark"/>
      <tagButton name="下载本页原视频" @click="handleDownload"/>
    </div>
    <!-- 查询结果 -->
    <MCTable :data-source="dataSource"/>
    <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="sizeChange" />
    <!-- 修改弹窗 -->
    <el-dialog v-if="dialogFormVisible" :visible.sync="dialogFormVisible" class="dialog" title="修改" style="width: 100%;" close>
      <el-form ref="form" label-width="80px">
        <el-form-item label="素材名称">
          <el-input v-model="updataQuery.title" clearable class="" style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="节目分类">
          <el-select v-model="updataQuery.lenType" class="select" placeholder="请选择">
            <el-option
              v-for="item in lenTypeFormat"
              :key="item.value"
              :label="item.value"
              :value="item.key"/>
          </el-select>
        </el-form-item>
        <el-form-item label="地区">
          <el-cascader
            v-model="updataQuery.loc"
            :options="cityList"
            :props="{
              expandTrigger: 'hover',
              value:'id',
              label:'name'
            }"
          />
        </el-form-item>
        <el-form-item label="标签">
          <el-cascader
            v-model="updataQuery.cateList"
            :options="cateOptions"
            :props="{
              expandTrigger: 'hover',
              value:'id',
              label:'name',
              multiple: true
            }"
          />
        </el-form-item>
        <el-form-item label="图片">
          <img-upload
            :file-list="updataQuery.picList"
            @onSuccess="uploadCallback"
            @onRemove="uploadCallback"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <!-- 预览 -->
    <el-dialog
      :visible.sync="dialogView"
      :show-close="true"
      width="25%"
      title="预览"
      custom-class="views"
      @closed="video.sourceUrl = undefined"
    >
      <div id="mainContainer" class="" style="width:95%;margin:auto;">
        <live-video-area-view
          v-if="video && video.sourceUrl"
          id="mainPlayer"
          ref="mainPlayer"
          :url="video.sourceUrl"
          style="width: 100%; height: 100%;"/>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import BackToTop from '../../../components/BackToTop'
import Pagination from '../../../components/Pagination'
import { apiMeterial } from '../../../api/mediaManage/index'
import { apiCommon } from '../../../api/common'
import Fn from '../../../utils/fn'
import { FileUtil } from '../../../utils/file-util'
import ObjectUtil from '../../../utils/object-util'
import { apiVideo as API } from '../../../api/clip/task'
import tagButton from '../../../components/common/tagButton'
import LiveVideoAreaView from '../clip/views/LiveVideoAreaView'
import tableColumns from './columnsData/videoListColums'
import { sourceFormat, lenTypeFormat } from '../../../mixin/MixinContants'
import imgUpload from '../../../components/common/imgUpload'
import clipboard from '../../../utils/clipboard'
export default {
  name: 'RadioProgramList',
  inject: ['reload'],
  components: { BackToTop, Pagination, tagButton, LiveVideoAreaView, imgUpload },
  mixins: [
    sourceFormat.mixin,
    lenTypeFormat.mixin
  ],
  data() {
    return {
      dataSource: {
        headerLines: 2,
        list: [],
        columns: tableColumns,
        operates: {
          fixed: 'right',
          width: '250',
          list: [
            { label: '修改', type: 'warning', show: (row) => (true),
              method: (index, row) => {
                this.handleedit(row)
              }
            },
            { label: '移到回收站', type: 'danger', show: (row) => (true),
              method: (index, row) => {
                this.handledel(row.id)
              }
            },
            { label: '预览', type: 'info', show: (row) => (row.source != 1),
              method: (index, row) => {
                this.views(row)
              }
            },
            { label: '下载', type: 'info', show: (row) => (row.source != 1),
              method: (index, row) => {
                this.oneDownload(row)
              }
            }
          ]
        }
      },
      dialogView: false,
      // 分类表
      cateOptions: [],
      // 搜索绑定的分类
      cateList: [],
      // 地区表
      cityList: [],
      page: 1,
      total: 0,
      // 列表和搜索参数
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        beginTime: undefined,
        endTime: undefined,
        source: undefined,
        cateOne: undefined,
        cateTwo: undefined,
        type: 1,
        auditStatus: 1,
        inTrash: 0,
        playId: undefined,
        keywords: undefined
      },
      dialogFormVisible: false,
      // 素材更新的参数
      updataQuery: {
        id: undefined,
        cateOneList: [],
        cateTwoList: [],
        type: 1,
        title: undefined,
        cateList: []

      },
      video: { sourceUrl: undefined }

    }
  },
  created() {
    this.Init()
  },
  methods: {
    // 复制
    copy(text) {
      clipboard(text, '.copy')
    },
    /**
     * @name: 上传组件回调
     * @param {*} fileList 上传文件列表
     * @param {*} updataQuery 更新的params
     * @return {*}
     */
    uploadCallback(fileList) {
      const success = fileList.every(item => item.status === 'success')
      if (success) {
        this.updataQuery.picList =
        fileList.map(item => ({ url: item.response ? item.response.datas.url : item.url }))
      }
    },
    // 预览
    views(row) {
      if (row.downUrl) {
        this.video.sourceUrl = row.downUrl
      } else if (row.markUrl) {
        this.video.sourceUrl = row.markUrl
      } else if (row.url) {
        this.video.sourceUrl = row.url
      } else {
        return this.toast.fail('暂时无法预览')
      }
      this.dialogView = true
    },
    // 单独下载
    oneDownload: Fn.Confirm(function(row) {
      const loading = this.$loading({
        lock: true,
        text: '下载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const finalName = (row.title || '') + '_视频下载'
      if (ObjectUtil.notEmpty(row.downUrl)) {
        const pArr = []
        let fileDataList = []
        fileDataList = [{ filename: row.title + '.mp4', data: null }]
        pArr.push(API.file(row.downUrl)())
        Promise.all(pArr).then(resList => {
          console.log(resList, 'reslist')
          resList.forEach((data, index) => {
            console.log(data, index)
            fileDataList[index].data = data.data
          })
          FileUtil.fileBatchDownload(finalName, fileDataList).then(downRes => {
            this.$notify.success({
              title: '成功',
              message: '下载成功'
            })
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
            })
          }).finally(() => {
            loading.close()
          })
        })
      }
    }),
    // 地区格式化
    formatLoc(loc) {
      let cityInfo = []
      this.cityList && this.cityList.forEach(p => {
        p.children && p.children.forEach(c => {
          if (c.id == loc) {
            cityInfo = [p.id, c.id]
          }
        })
      })
      return cityInfo
    },
    /**
     * 格式化分类数据
     * @argument type 1[[...],[...]] to 一级:[],二级:[]  2一级:[],二级:[] to [[...],[...]]
    */
    formatCate(type, cateList) {
      let cateInfo = null
      let filterData = null
      if (type == 1) {
        filterData = [...new Set([].concat(...cateList))]
        cateInfo = { cateOneList: [], cateTwoList: [] }
        filterData.forEach(item => {
          this.cateOptions.forEach(cate => {
            if (item == cate.id) {
              cateInfo.cateOneList.push({ ...cate })
            } else {
              cate.children && cate.children.forEach(c => {
                if (item == c.id) {
                  cateInfo.cateTwoList.push({ ...c })
                }
              })
            }
          })
        })
      } else {
        cateInfo = []
        cateList && cateList.forEach(item => {
          item.children.forEach(c => {
            cateInfo.push([item.id, c.id])
          })
        })
      }
      return cateInfo
    },
    // tree结构格式化，去二级children
    formatList(list) {
      list.forEach(item => {
        item.children.forEach(c => {
          c.children = undefined
        })
      })
      return list
    },
    // 省市信息
    getAreaList() {
      return new Promise((resolve, reject) => {
        apiCommon.arealist().then(res => {
          if (res.data.resp_code == 0) {
            this.cityList = this.formatList(res.data.datas)
            resolve(res.data.datas)
          } else {
            this.toast.fail(res.data.resp_msg)
            reject(res)
          }
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
          })
          reject(response)
        })
      })
    },
    // 获取关联的分类信息
    relationCategory() {
      return new Promise((resolve, reject) => {
        apiMeterial.relationCategory().then(res => {
          if (res.data.resp_code == 0) {
            this.cateOptions = this.formatList(res.data.datas)
            resolve(res.data.datas)
          } else {
            this.toast.fail(res.data.resp_msg)
            reject(res.data)
          }
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
          })
          reject(response)
        })
      })
    },
    // 全部下载
    handleDownload: Fn.Confirm(function() {
      const loading = this.$loading({
        lock: true,
        text: '下载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const finalName = '视频下载集合'
      const clipList = this.dataSource.list || []
      const pArr = []
      const fileDataList = []
      clipList.filter(clip => ObjectUtil.notEmpty(clip.orgUrl)).forEach(clip => {
        fileDataList.push({ filename: clip.title + '.mp4', data: null })
        pArr.push(API.file(clip.orgUrl)())
      })

      Promise.all(pArr).then(resList => {
        resList.forEach((data, index) => {
          console.log(data, index)
          fileDataList[index].data = data.data
        })
        FileUtil.fileBatchDownload(finalName, fileDataList).then(downRes => {
          this.$notify.success({
            title: '成功',
            message: '下载成功'
          })
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
          })
        }).finally(() => {
          loading.close()
        })
      })
    }),
    sizeChange(val) {
      this.listQuery.limit = val.limit
      this.getList()
    },
    // 加水印
    addWatermark: Fn.Confirm(async function() {
      const idList = this.dataSource.list.map(item => item.id)
      const [err, res] = await this.$await(apiMeterial.addWatermark({ idList }))
      if (res) {
        this.toast.success('成功')
        this.getList()
      }
    }),
    // 重置页面
    refresh() {
      this.reload()
    },
    // 点击修改
    handleedit(row) {
      const picList = row.picList ? JSON.parse(row.picList).map(item => ({ url: item })) : []
      this.updataQuery = {
        ...row,
        cateList: this.formatCate(2, row.cateTrees),
        loc: this.formatLoc(row.loc) || [],
        picList
      }
      this.dialogFormVisible = true
    },
    // 确认修改
    async updateData() {
      const { loc, cateList } = this.updataQuery
      const { cateOneList, cateTwoList } = this.formatCate(1, cateList)
      const picList = JSON.stringify(this.updataQuery.picList.map(item => (item.url)))
      const queryParams = {
        ...this.updataQuery,
        loc: loc[1],
        cateOneList,
        cateTwoList,
        picList,
        cateList: undefined
      }
      const [err, res] = await this.$await(apiMeterial.updateList(queryParams))
      if (res) {
        this.toast.success('修改成功')
        this.dialogFormVisible = false
        this.getList()
      }
    },
    // 移到回收站
    handledel: Fn.Confirm(async function(id) {
      const [err, res] = await this.$await(apiMeterial.inTrash({ id, inTrash: 1 }))
      if (res) {
        this.toast.success('移除成功')
        this.getList()
      }
    }, '确认移到回收站？'),
    // 初始化页面
    Init() {
      this.getList()
      this.relationCategory()
      this.getAreaList()
    },
    // 搜索
    handleFilter() {
      console.log(this.listQuery)
      this.listQuery.page = 1
      if (this.cateList.length != 0) {
        this.listQuery.cateOne = this.cateList[0] || ''
        this.listQuery.cateTwo = this.cateList[1] || ''
      }
      this.getList()
    },
    // 列表数据
    async getList() {
      this.$set(this.dataSource, 'options', { loading: true })
      const [err, res] = await this.$await(apiMeterial.list({ ...this.listQuery }))
      if (res) {
        this.dataSource.list = res.datas.list || []
        this.total = Number(res.datas.total)
      }
      this.$set(this.dataSource, 'options', { loading: false })
    }
  }
}
</script>

<style lang='scss' scoped>
  ::v-deep .el-dialog__body{
    padding:0;
    padding-bottom: 10px;
  }
  .datasview{
    .buttons{
      margin: 10px 0;
      .el-tag{
        cursor: pointer;
      }
    }
    .search{
      div{
        display: inline-block;

      }
    }
    .content{
      width:100%;
      height:auto;
      display: flex;
      justify-content: space-around;
      .left,.right{
        border:1px solid #ccc;
        // flex: 1;
        margin:0 10px;
        padding:15px;

      }
      .left{
        width:30%;
        .list{
          p{
            overflow: hidden;
            padding:10px 6px;
            & span:first-child{
              float: left;
            }
            & span:last-child{
              float: right;
            }
            // display: flex;
            // justify-content: space-around;
          }
        }
      }
      .right{
        width:60%;
        .list{
          width:100%;
          p{
            overflow: hidden;
            padding:10px 6px;
            width:100%;
            display: flex;
            justify-content: space-around;
          }
        }
      }
    }
  }
</style>
